package com.bw.mallclient.test;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.bw.mallclient.R;

import org.jetbrains.annotations.NotNull;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

public class ViewModelActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView vm_tv;
    private TestViewModel vm;
    private  Observer<String>dataOB;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewmodel);
        vm = new ViewModelProvider(this, new ViewModelProvider.Factory() {
            @NonNull
            @NotNull
            @Override
            public <T extends ViewModel> T create(@NonNull @NotNull Class<T> modelClass) {
                return (T) new TestViewModel();
            }
        }).get(TestViewModel.class);
        vm_tv = findViewById(R.id.vm_tv);
        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        dataOB = new Observer<String>() {
            @Override
            public void onChanged(String s) {
                vm_tv.setText(s);
            }
        };
        vm.data.observe(this, dataOB);
    }

    @Override
    protected void onPause() {
        super.onPause();
        vm.data.removeObserver(dataOB);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.btn1 == id){
            vm.data.setValue("hehe");
        }else {
            String str = vm.data.getValue();
            Log.e("ZXY","str:"+str);
        }
    }
}
